<template>
    <ConfirmDialog
        :layer="props"
        @update:visible="updateDialogShow"
        @confirm="submit">
        <el-form
            class="edit-application-form"
            ref="formRef" 
            :model="form" 
            :rules="rules"
            label-width="100px">
            <el-form-item prop="dataType" label="应用">
                <span v-if="isEdit">{{form.appTypeShowName}}</span>
                <el-select
                    v-else
                    v-model="form.dataType"
                    clearable
                    placeholder="请选择"
                    @change="handleDataType">
                    <el-option
                        v-for="item in applicationTypeList"
                        :key="item.key"
                        :label="item.name"
                        :value="item.key"
                    />
                </el-select>
            </el-form-item>
            <!-- 类型为课程质量检测，不配置应用 -->
            <el-form-item v-if="form.dataType != 'monitor'" prop="componentList" label="配置应用">
                 <el-button 
                    :disabled="!form.dataType"
                    @click="toAddComponent" 
                    class="common-text-btn"
                    v-if="!isEdit"
                >添加组件</el-button>
                <!-- 专题 -->
                <div class="component-list"  v-if="form.dataType == 'topic'">
                    <div v-for="(item, index) in data.authComponentList" :key="item.id" class="item">
                        <div class="row">
                            <span class="label label-title">标题：</span>
                            <span>{{ item.title || item.name }}</span>
                        </div>
                        <div class="row">
                            <span class="label">学科学段：</span>
                            <span>{{ fmtName(item.stageSubjectList) }}</span>
                        </div>
                        <el-icon @click="removeComponent(item, index)" class="del-btn" v-if="!isEdit">
                            <Delete />
                        </el-icon>
                    </div>
                </div>
                 <!-- 内容组 -->
                <div class="component-list"  v-else-if="form.dataType == 'group'">
                    <div v-for="(item, index) in data.componentList" :key="item.id" class="item">
                        <div class="row">
                            <span class="label label-title">标题：</span>
                            <span>{{ item.appExplain || item.name }}</span>
                        </div>
                        <div class="row">
                            <span class="label">学科学段：</span>
                            <span>{{ fmtName(item.stageSubjectList) }}</span>
                        </div>
                        <div class="row">
                            <span class="label">类型：</span>
                            <span>{{ item.appTypeName || form.appTypeShowName}}</span>
                        </div> 
                        <el-icon :size="20" @click="removeComponent(item, index)" class="del-btn" v-if="!isEdit">
                            <Delete />
                        </el-icon>
                    </div>
                </div>
                <!-- 同步备课 -->
                <div class="component-list"  v-else-if="form.dataType == 'lesson'">
                    <div v-for="(item, index) in data.componentList" :key="item.id" class="item">
                        <div class="row">
                            <span class="label">组件：</span>
                            <span>{{ item.componentName }}</span>
                        </div>
                        <div class="row" >
                            <span class="label">资源：</span>
                            <span>{{ item.resourceText }}</span>
                        </div>
                        <el-icon @click="deleteComponent(item, index)" class="del-btn" v-if="!isEdit">
                            <Delete />
                        </el-icon>
                    </div>
                </div>
            </el-form-item>
            <el-form-item prop="description" label="应用说明">
                <el-input
                    v-model.trim="form.description"
                    type="textarea"
                    :minlength="1"
                    :maxlength="200"
                    :rows="3"
                    show-word-limit
                    clearable
                    placeholder="请填写内容类型、范围等信息，便于后续维护">
                </el-input>
            </el-form-item>
            <el-form-item prop="time" label="设置有效期">
                <DateRange
                    ref="dateRangeRef"
                    :start-time="form.time.startTime"
                    :end-time="form.time.endTime"/>
                <!-- <div class="date-range-wrap">
                    <el-date-picker
                        v-model="form.time.startTime"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择"/>
                    <span>~</span>
                    <el-date-picker
                        v-model="form.time.endTime"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择"/>
                </div> -->
            </el-form-item>
            <el-form-item prop="acquireType" label="付费类型">
                <el-radio-group v-model="form.acquireType">
                    <el-radio :label="1">正式</el-radio>
                    <!-- 专题和内容组不能试用 -->
                    <el-radio v-if="form.dataType != 'topic' &&  form.dataType != 'group'" :label="0">试用</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
    </ConfirmDialog>
</template>

<script setup>
import ConfirmDialog from '@/components/dialogComp.vue';
import DateRange from '@/components/date-range.vue';
import { Delete } from '@element-plus/icons-vue';
import { ref, reactive, defineProps, defineEmits, watch, nextTick, computed } from 'vue';
import { useStore } from 'vuex';
import Fn from '@/lib/fn.js';
import { fmtStageName } from '@/lib/tools.js';
import Dayjs from 'dayjs';

const store = useStore();

const emit = defineEmits(['update:show']);

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    title: {
        type: String,
        default: '新增应用'
    },
    showButton: {
        type: Boolean,
        default: true
    },
    isCenter: {
        type: Boolean,
        default: false 
    },
    editStatus: {
        type: String,
        default: 'add'
    }
})

const isEdit = computed(() => {
    return props.editStatus === 'edit';
})

const formRef = ref(null);

// 表单数据
const form = reactive({
    dataType: 'topic', // 应用
    description: '',
    time: {
        startTime: '',
        endTime: ''
    },
    acquireType: 1 // 0-试用 1-正式
});

// 其他数据
const data = reactive({
    componentList: [], // 组件数据
    oldDataType: '', // 旧的组件类型数据
    authComponentList: [],
    tableSelectedIds: [],
    applySelectList: {
        topic: '专题',
        lesson: '学科产品(备课)',
        group: '内容组',
        monitor: '课程质量监测'
    }
})

// 应用类型组件
const applicationTypeList = ref([
    {name: '专题', key: 'topic'},
    {name: '学科产品(备课)', key: 'lesson'},
    {name: '内容组', key: 'group'},
    {name: '课程质量监测', key: 'monitor'}
]);

const dateRangeRef = ref(null);

// 校验时间
const timeValidator = (rule, value, callback) => {
    let startTime = Dayjs(value.startTime).valueOf() || '', 
    endTime = Dayjs(value.endTime).valueOf() || '';
    if(endTime == '' || startTime == '') {
        callback(new Error('请设置有效期'));
    }
    if(startTime && endTime && (startTime > endTime)) {
        callback(new Error('截止时间应在开始时间之后'));
    } 
    callback();
}

// 校验组件
const componentValidator = (rule, value, callback) => {
    callback();
}

// 表单校验规则
const rules = {
    dataType: [{ required: true, message: '请选择应用类型', trigger: 'change'}],
    description: [{ required: true, message: '请输入应用说明', trigger: 'blur'}],
    time: [{ required: false, validator: timeValidator }],
    acquireType: [{ required: false, message: '请选择付费类型', trigger: 'change'}],
    componentList: [{ required: true, validator: componentValidator }]
}

// 更改弹窗显隐
const updateDialogShow = () => {
    emit('update:show', !props.show);
}

// 提交表单数据
const submit = () => {
    let timeInfo = dateRangeRef.value.getDateRange();
    form.time.startTime = timeInfo.startTime;
    form.time.endTime = timeInfo.endTime;
    formRef.value.validate(valid => {
        if (!valid) {
            return;
        }
        console.log('submit');
    })
}

// 切换应用判断当前配置应用
const handleDataType = (newVal) => {
    Fn.Confirm(() => {
        console.log(123);
    }, 
    '您确认要切换应用吗？如果切换您当前添加的应用将丢失奥',
    '提示',
    () => {
        form.dataType = data.oldDataType;
    }
    )();
    // 内容组李爱玲要求有效期是2022年4月1日到2032年4月1日
    if (form.dataType == 'group') {
        form.time.startTime = '2022-04-01'
        form.time.endTime = '2032-04-01'
    } else {
        form.time.startTime = ''
        form.time.endTime = ''
    }
}

// 删除组件
const deleteComponent = (data, index) => {
    Fn.Confirm(() => {
        store.dispatch('message', {
            message: '删除成功'
        });
       data.componentList.splice(index, 1);
    }, 
    '删除后将不可恢复，是否确认删除？',
    '删除')();
}

// 移除组件
const removeComponent = (data, index) => {
    Fn.Confirm(() => {
        // self.$refs.disposeModal 
        // && self.$refs.disposeModal.$refs.authView 
        // && self.$refs.disposeModal.$refs.authView.onCancel(data)
        store.dispatch('message', {
            message: '删除成功'
        });
       data.componentList.splice(index, 1);
       data.authComponentList.splice(index, 1);
       data.tableSelectedIds.splice(index, 1);
    }, 
    '是否确认删除？',
    '删除')();
}

// 显示配置组件弹窗
const toAddComponent = () => {}

// 格式化学段学科
const fmtName = (stageList) => {
    return fmtStageName(stageList);
}

// 监听应用类型更改，记住旧的应用类型，用于取消切换应用类型
watch(() => form.dataType, (newVal, oldVal) => {
    data.oldDataType = oldVal;
})

// 监听弹窗显隐，清空弹窗数据
watch(() => props.show, (val) => {
    if (val) {
        // 打开弹窗，重置表单数据
        nextTick(() => {
            console.log('reset');
            data.componentList = [];
            data.authComponentList = [];
            formRef.value.resetFields();
            form.time.startTime = '';
            form.time.endTime = '';
            dateRangeRef.value.resetDateRange();
        });
    }
});

</script>

<style lang="scss" scoped>
.date-range-wrap {
    display: flex;
}
</style>